<template>
    <div style="padding-top: 79px;">
        <div class="editor-box">
            <el-form :model="video" :rules="rules" ref="ruleForm" label-width="100px" >
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="文章标题" prop="title">
                            <el-input v-model="video.title"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="文章简介" prop="summary">
                            <el-input v-model="video.summary"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="文章标签" prop="tagList">
                            <el-select v-model="video.tagList" :multiple-limit="3" multiple placeholder="请选择标签">
                                <el-option v-for="item in tagList" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="文章分类" prop="categoryId">
                            <el-select v-model="video.categoryId" placeholder="请选择分类">
                                <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="创作类型" prop="isOriginal">
                            <el-radio v-model="video.isOriginal" border :label="1">原创</el-radio>
                            <el-radio v-model="video.isOriginal" border :label="0">转载</el-radio>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20" v-if="video.isOriginal == 0">
                    <el-col :span="8">
                        <el-form-item label="文章地址" prop="originalUrl">
                            <el-input v-model="video.originalUrl"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="文章内容" prop="contentMd">
                    <!--mavon-editor的主体-->
                    <mavon-editor
                            ref="md"
                            v-model="video.contentMd"
                            :xssOptions="{whiteList: {iframe: ['src', 'height', 'width'],div: ['style', 'height', 'width', 'align'],},}"
                    >

                        <!-- 引用视频链接的自定义按钮 -->
                        <template v-slot:left-toolbar-after>
                            <!--点击按钮触发的事件是打开表单对话框-->
                            <el-button type="text" @click="dialogFormVisible=true" aria-hidden="true" class="op-icon fa" title="插入视频资源">
                                <i class="el-icon-video-camera-solid" style="margin-right: 10px;background-color: #eeff02;width: 20px;height: 20px"/>   点击插入视频资源
                            </el-button>
                        </template>
                    </mavon-editor>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialogFooter">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="submit">提交审核</el-button>
        </span>
        </div>
        <!-- 插入视频链接的dialog提示框，表单对话框 -->
        <el-dialog title="插入视频资源" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item label="视频链接" :label-width="formLabelWidth">
                    <el-input v-model="form.link" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="链接类型" :label-width="formLabelWidth">
                    <el-select v-model="form.region" placeholder="请选择链接类型">
                        <el-option label="iframe标签" value="iframe"></el-option>
                        <el-option label="url链接" value="url"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <!--单机确定按钮后触发 videoLink事件函数，开始格式化链接格式并插入到文本域-->
                <el-button type="primary" @click="videoLink">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 错误提示框 -->
        <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%"
                id="link-error">
            <span>视频链接格式错误，请重新确认后再输入！</span>
            <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
        </el-dialog>

    </div>
</template>

<script>
    import {featchCategory, fetchTagList, getMyArticleInfo, insertArticle} from "@/api";

    export default {
        data() {
            return {
                video:{},
                title:'',
                tagList:[],
                rules:{},
                categoryList:[],
                toolbars: {
                    // 工具栏设定可以参考官方文档
                },
                value: '',	// 存放 mavon-editor 文本域的内容
                dialogFormVisible: false,	// 用于控制表单对话框的开启和关闭
                dialogVisible: false,		// 用于控制错误提示对话框的开启和关闭
                formLabelWidth: '120px',	// 设定表单对话框内表单是宽度
                form: {		// 表单对话框内表单的数据
                    link: '',
                    region: ''
                }
            }
        },
        computed: {
            drawer: {
                set(value) {
                    this.$store.state.articleDrawer.flag = value;
                },
                get() {
                    if (this.$store.state.articleDrawer.flag) {
                        this.article = {
                            isOriginal: 1,
                            avatar: null,
                        }
                        featchCategory().then(res => {
                            this.categoryList = res.data
                        })
                        fetchTagList().then(res => {
                            this.tagList = res.data
                        })
                        if (this.$store.state.articleDrawer.id) {

                            getMyArticleInfo(this.$store.state.articleDrawer.id).then(res => {
                                this.article = res.data
                            })
                        }
                    }
                    return this.$store.state.articleDrawer.flag;
                }
            },
        },
        methods: {
            submit() {
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        if (!this.article.contentMd) {
                            this.$message.error("请编写文章内容！")
                            return;
                        }
                        insertArticle(this.article).then(res => {
                            this.$store.state.articleDrawer.flag = false
                            this.$message.success("提交成功，请耐心等待审核")
                        }).catch(err => {
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            handleClose() {
                this.$confirm('确认关闭吗？编写的文章不会保存哦', '提示', {
                    lockScroll: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(_ => {
                        this.$store.state.articleDrawer.flag = false
                    })
                    .catch(_ => {
                        this.$message.info("取消关闭")
                    });
            },
            // 格式化视频链接并插入到文本域的函数
            videoLink() {
                // 准备链接模板
                let linkFrame = '';
                let linkFrameStart = "<div align=center width=100%><iframe height=500 width=80% src='"
                let linkFrameEnd = "' frameborder=0 'allowfullscreen'></iframe></div>"
                // 创建一个div盒子，为提取src做准备
                var box = document.createElement("div");
                // 将原始链接插入到盒子中
                box.innerHTML=this.form.link;
                // 判断不同的视频原链接类型
                if(this.form.region == "url"){
                    linkFrame = linkFrameStart + this.form.link + linkFrameEnd;
                }else if(this.form.region == "iframe" && box.getElementsByTagName("iframe").length > 0) {
                    // 从iframe标签中提取src属性
                    linkFrame = linkFrameStart + box.getElementsByTagName("iframe")[0].getAttribute("src") + linkFrameEnd;
                }else {
                    // 原始链接格式错误时弹出错误提示
                    this.dialogFormVisible=false;
                    this.dialogVisible=true;
                }
                // 复原表单文本框内容
                this.form.link = '';
                this.form.region = '';

                // 获取文本域中当前光标起始位置、结束位置以及滚动条位置（滚动条位置我认为没有必要，如有需要可以自己取消注释）
                let textarea = document.getElementsByClassName("auto-textarea-input")[0];
                let posStart = textarea.selectionStart;
                let posEnd = textarea.selectionEnd;
                // let posScroll = document.getElementsByClassName("v-note-edit")[0].scrollTop;
                // 获取文本域中未选中的的前半部分和后半部分，以被选中内容起始和结束位置做分割点
                let subStart = this.$refs.md.d_value.substring(0, posStart);
                let subEnd = this.$refs.md.d_value.substring(posEnd, this.$refs.md.d_value.length);
                // 拼接并替换文本域内容
                this.$refs.md.d_value = subStart + '\n' + linkFrame + '\n' + subEnd;
                // document.getElementsByClassName("v-note-edit")[0].scrollTop = posScroll;

                // 关闭对话框
                this.dialogFormVisible = false;
            }
        },

    }
</script>

<style>
    .dialogFooter {
        margin-left: 1200px;
    }
</style>


